package com.java.base.javabase.images;


import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;


public class TestImage {

    private static final Logger log = LoggerFactory.getLogger(TestImage.class);

    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        String backgroundUrl = "http://picspy.lexue.com/avatar-employee-1593742719339";
        String wechatImageUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/TdCpAT2YpDaLIWmwRoukpGEUaI8AZ8cgzEBOsKVN7zdHUUhtZ2UqY6BJBWicMTcHCkjU0uI25ia20ATI6em5QdYw/132";
        String codeContent = "http://thirdwx.qlogo.cn/mmopen/vi_32/TdCpAT2YpDaLIWmwRoukpGEUaI8AZ8cgzEBOsKVN7zdHUUhtZ2UqY6BJBWicMTcHCkjU0uI25ia20ATI6em5QdYw/132";
        String classIntrodeceUrl = "http://picspy.lexue.com/avatar-employee-1593417967886";
        String wechatName = "柴火火";
        String tempImagePath = "D:/" + System.currentTimeMillis() + ".png";;
        String teacherName = "啊啊啊啊大师";
        Integer supportCount = 100;
        BigDecimal classPrice = new BigDecimal("10000");

        String base64 = creatShareImage(backgroundUrl, wechatImageUrl, codeContent, wechatName, tempImagePath,classIntrodeceUrl,
                teacherName, supportCount, classPrice);
        System.out.println(base64);
    }



    public static String creatShareImage(String backgroundUrl, String wechatImageUrl, String codeContent, String wechatName,
                                         String tempImagePath, String classIntrodeceUrl,
                                         String teacherName, Integer supportCount, BigDecimal classPrice){


        try {
             // 获取背景图片流对象
            InputStream is  = new ByteArrayInputStream(HttpUtil.downloadBytes(backgroundUrl));
            BufferedImage backgroudImage = ImageIO.read(is);
            log.info("<<< 背景图片的高：[{}],宽：[{}]", backgroudImage.getHeight(), backgroudImage.getWidth());
            //ImageIO.write(backgroudImage, "png", new File("D:/tset.png"));
            // 微信头像
            InputStream wechatin  = new ByteArrayInputStream(HttpUtil.downloadBytes(wechatImageUrl));
            BufferedImage wechatHeadImage = ImageIO.read(wechatin);
            // 先缩小微信头像图片
            BufferedImage  headImage = zoomImage(wechatHeadImage, 100, 100);
            //ImageIO.write(headImage, "png", new File("D:/wechatHeadImage.png"));

            BufferedImage circularBufferQRImage = roundImage(headImage,headImage.getWidth(),headImage.getWidth());
            //ImageIO.write(circularBufferQRImage, "png", new File("D:/circularBufferQRImage.png"));
            log.info("<<< 微信头像图片的高：[{}],宽：[{}]", wechatHeadImage.getHeight(), wechatHeadImage.getWidth());
            // 二维码图片 --- 生成二维码并返回生成二维码的存储路径
            BufferedImage qrBufferedImage  = QRBarCodeUtil.createCodeBufferedImage(codeContent, null, 215 ,215);

            // 班级介绍图片
            InputStream classIntrodeceIs  = new ByteArrayInputStream(HttpUtil.downloadBytes(classIntrodeceUrl));
            BufferedImage classIntrodeceImage = ImageIO.read(classIntrodeceIs);
            // 扩大班级介绍图片
            BufferedImage  classIntrodece = zoomImage(classIntrodeceImage, 689, 387);

            // 获取系统支持的字体
            GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); //返回本地 GraphicsEnvironment 。
            String [] systemFontName = e.getAvailableFontFamilyNames(); //返回包含在此所有字体系列名称的数组， GraphicsEnvironment本地化为默认的语言环境，如返回 Locale.getDefault() 。
            log.info("<<< 当前系统支持的 字体库有：[{}]", JSONObject.toJSONString(systemFontName));
            String fontName;
            if(systemFontName.length < 1) {
                log.info("<<< 当前系统支持的 字体库异常请联系管理员");

            }
            fontName = systemFontName[0];
            log.info(">>> 当前选中的字体库为:[{}]", fontName);

            // 开启画笔
            Graphics2D graphics = backgroudImage.createGraphics();
            // 在背景图片上添加微信名称
            graphics.setFont(new Font(fontName, Font.BOLD ,40));
            graphics.drawString(wechatName, 54+(12-wechatName.length())*12, 80);

            // 介绍信息
            StringBuffer userIntrodeceInfo = new StringBuffer("我正在报名").append(teacherName).append("大师课，快来祝我一臂之力，帮我免费拿下课程!");

            if(userIntrodeceInfo.length() < 22) {
                graphics.setFont(new Font(fontName, Font.PLAIN ,24));
                graphics.drawString(userIntrodeceInfo.toString(), 172, 127);
            }
            else {
                graphics.setFont(new Font(fontName, Font.PLAIN ,24));
                graphics.drawString(userIntrodeceInfo.substring(0, 22), 172, 127);
                graphics.drawString(userIntrodeceInfo.substring(22, userIntrodeceInfo.length()), 172, 159);
            }

            // 课程说明信息
            StringBuffer classIntrodeceInfo = new StringBuffer("邀请").append(supportCount).append("位同学助力，即可免费领取价值").append(classPrice).append("元的大师课!");
            graphics.setColor(Color.BLACK);
            if(classIntrodeceInfo.length() < 18) {
                graphics.setFont(new Font(Font.DIALOG, Font.BOLD ,34));
                graphics.drawString(classIntrodeceInfo.toString(), 61, 651);
            }
            else {
                graphics.setFont(new Font(fontName, Font.BOLD ,34));
                graphics.drawString(classIntrodeceInfo.substring(0, 18), 61, 651);
                graphics.drawString(classIntrodeceInfo.substring(18, classIntrodeceInfo.length()), 61, 701);
            }



            // 拼装微信头像到主图上
            graphics.drawImage(circularBufferQRImage, 32, 40, circularBufferQRImage.getWidth(), circularBufferQRImage.getHeight(), null);

            // 在背景图片上添加二维码图片
            graphics.drawImage(qrBufferedImage, 265, 807, qrBufferedImage.getWidth(), qrBufferedImage.getHeight(), null);

            // 在背景图片上班级介绍图片
            graphics.drawImage(classIntrodece, 31, 209, classIntrodece.getWidth(), classIntrodece.getHeight(), null);


            graphics.dispose();


            // 本地保存图片

            ImageIO.write(backgroudImage, "png", new File(tempImagePath));
            // 输出新的图片
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean flag = ImageIO.write(backgroudImage, "png", out);
            byte[] b = out.toByteArray();
            String base64Code = Base64.encode(b);
            return tempImagePath;
        }  catch (Exception e) {
            //throw new ServiceException("获取二维码图片异常");

        }

        return null;
    }


    /*
     * 图片缩放,w，h为缩放的目标宽度和高度
     * src为源文件目录，dest为缩放后保存目录
     */
    public static BufferedImage zoomImage(BufferedImage bufImg,int w,int h) throws Exception {
        double wr=0,hr=0;

        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放目标图片模板

        wr=w*1.0/bufImg.getWidth();     //获取缩放比例
        hr=h*1.0 / bufImg.getHeight();
        try {
            AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
            Itemp = ato.filter(bufImg, null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return (BufferedImage)Itemp;
    }




    private static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) {
        BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = outputImage.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return outputImage;
    }





}